import { ContentType } from "./ContentType";
import { Header } from "./Header";
import { RequestMethod } from "./RequestMethod";
import { Response } from "../response/Response";

export class Request{

    public method: RequestMethod;
    public url: string;
    public header: Header[];
    public contentType: ContentType;
    public data: any;

    constructor(url: string,contentType:ContentType,method?:RequestMethod,data?:any){
        this.contentType = contentType;
        this.method = method == undefined ? RequestMethod.GET : method;
        this.url = url;
        this.data = data;

        if(this.method == RequestMethod.GET){//两种写法都可以
            //this.url = this.url += "?" + this.contentType.dataHandle(this.data);
            this.url += ("?" + this.contentType.dataHandle(this.data));
        }
    };

    request(){
        return new Promise((resolve)=>{
            let xhr = new XMLHttpRequest();
            //载入请求open方法:请求方式,请求地址,是否异步
            
            xhr.open(this.method.name,this.url,true);
            //监听状态变化
            xhr.onreadystatechange = function(){
                if (xhr.readyState === 4 && xhr.status ===200){
                    //处理响应正文responseText,多数是json数据
                    var response = new Response(xhr);
                    resolve(response.body.toBean());
                }
            }
            if(this.method != RequestMethod.GET){
                xhr.setRequestHeader("Content-type",this.contentType.name);
                xhr.send(this.contentType.dataHandle(this.data));
            }else{
                xhr.send();
            }
        });
    }

}